<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/14
 * Time: 10:47
 */
namespace App\Http\Controllers;


use App\Service\DataReturnService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Common\Base;
use Illuminate\Support\Facades\Validator;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class ErweimaController extends Controller
{
    /**
     * @Notes:商品详情分享二维码
     * @param Request $request
     * @return array
     * @throws \Exception
     * @author: LiBaoJin
     * @Time:
     */
        public function create_detail_qrcode(Request $request)
        {
            $postData = ['token' => $request->get('token'), 'product_id' => $request->get('product_id')];
            $validator      = Validator::make($postData,[
                'token'   => 'required',
                'product_id'   => 'required',
            ]);
            if ($validator->fails()) {
                return DataReturnService::returnError(1000,'验证错误！',$validator->errors());
            }

            $userInfo = Base::getUserByToken($postData['token']);
            if($userInfo['code'] != '666'){
                return $userInfo;
            }
            $user   = $userInfo['data'];
            $app_data = DB::table('business')->where(['business_id'=>$user['business_id']])->first();
            $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$app_data->appid."&secret=".$app_data->secret;
            $json = $this->httpRequest($access_token );
            $json = json_decode($json,true);
            //width是二维码宽度
            $qcode = "https://api.weixin.qq.com/wxa/getwxacode?access_token=".$json['access_token'];
            $param = json_encode(array("path" => "pages/productdetail/productdetail?id=".$postData['product_id']."&user_id=".$user['id'], "width" => 150));
            //POST参数
            $result = $this->httpRequest($qcode, $param, "POST");
            //生成二维码
            $file_name = 'public/upload/'.time().rand(1000,9999).'.jpg';
            file_put_contents($file_name, $result);
          // $base64_image = base64_encode('data:image/png;base64'.$result);
            $qiniuConfig = config('app.qiniu');
            include 'app/Service/qiniu/php-sdk/autoload.php';
            $auth = new Auth($qiniuConfig['accessKey'], $qiniuConfig['secretKey']);
            $key = time().rand(1000,9999).'.jpg';
            $upToken = $auth->uploadToken($qiniuConfig['merchantBucket'],$key, 3600);//获取上传所需的toke
            $uploadMgr = new UploadManager();
            list($ret,$err) = $uploadMgr->putFile($upToken,$key,$file_name);
            if(empty($err)){
                unlink($file_name);  //删除本地图片
            }else{
                return DataReturnService::returnError(-1,'获取分享二维码失败',['']);
            }
            $ret['key'] = $qiniuConfig['merchantDomain']. $ret['key'];
            DB::table('share_product_miniapp')->insert([
                'user_id'        =>$user['id'],
                'product_id'    =>$postData['product_id'],
                'product_url'    =>$ret['key'],
                'state'           =>0,
                'create_time'    =>date('Y-m-d H:i:s'),
                'update_time'    =>date('Y-m-d H:i:s'),
            ]);
            return DataReturnService::returnOk($ret,'获取分享二维码成功');


        }

    /**
     * @Notes:小程序分享二维码
     * @param Request $request
     * @return array
     * @throws \Exception
     * @author: LiBaoJin
     * @Time:
     */
        public function create_qrcode(Request $request)
    {
        $postData = ['token' => $request->get('token')];
        $validator      = Validator::make($postData,[
            'token'   => 'required',
        ]);
        if ($validator->fails()) {
            return DataReturnService::returnError(1000,'验证错误！',$validator->errors());
        }

        $userInfo = Base::getUserByToken($postData['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];
        $app_data = DB::table('business')->where(['business_id'=>$user['business_id']])->first();
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$app_data->appid."&secret=".$app_data->secret;
        $json = $this->httpRequest($access_token );
        $json = json_decode($json,true);
        //width是二维码宽度
        $qcode = "https://api.weixin.qq.com/wxa/getwxacode?access_token=".$json['access_token'];
        $param = json_encode(array("path" => "pages/index/index?user_id=".$user['id'], "width" => 150));
        //POST参数
        $result = $this->httpRequest($qcode, $param, "POST");
        //生成二维码
        $file_name = 'public/upload/'.time().rand(1000,9999).'.jpg';
        file_put_contents($file_name, $result);
        // $base64_image = base64_encode('data:image/png;base64'.$result);
        $qiniuConfig = config('app.qiniu');
        include 'app/Service/qiniu/php-sdk/autoload.php';
        $auth = new Auth($qiniuConfig['accessKey'], $qiniuConfig['secretKey']);
        $key = time().rand(1000,9999).'.jpg';
        $upToken = $auth->uploadToken($qiniuConfig['merchantBucket'],$key, 3600);//获取上传所需的toke
        $uploadMgr = new UploadManager();
        list($ret,$err) = $uploadMgr->putFile($upToken,$key,$file_name);
        if(empty($err)){
            unlink($file_name);  //删除本地图片
        }else{
            return DataReturnService::returnError(-1,'获取分享商品二维码失败',['']);
        }
        $ret['key'] = $qiniuConfig['merchantDomain']. $ret['key'];
        DB::table('share_product_miniapp')->insert([
                        'user_id'        =>$user['id'],
                        'miniapp_url'    =>$ret['key'],
                        'state'           =>0,
                        'create_time'    =>date('Y-m-d H:i:s'),
                        'update_time'    =>date('Y-m-d H:i:s'),
        ]);
        return DataReturnService::returnOk($ret,'获取分享商品二维码成功');


    }
            //把请求发送到微信服务器换取二维码
        public function httpRequest($url, $data = '', $method = 'GET')
            {
                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, $url);
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
                curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
                if ($method == 'POST') {
                    curl_setopt($curl, CURLOPT_POST, 1);
                    if ($data != '') {
                        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                    }
                }

                curl_setopt($curl, CURLOPT_TIMEOUT, 30);
                curl_setopt($curl, CURLOPT_HEADER, 0);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                $result = curl_exec($curl);
                curl_close($curl);
                return $result;
            }

    /**
     * @Notes:收集分享
     * @param Request $request
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
        public function get_be_shared(Request$request){
            $postData = ['token'      => $request->post('token'),
                        'parent_id'  => $request->post('parent_id'),
                        'product_id'  => $request->post('product_id'),
                        'product_url' => $request->post('product_url'),
                        'miniapp_url' => $request->post('product_url'),
                        ];
            $validator      = Validator::make($postData,[
                'token'   => 'required',
            ]);
            if ($validator->fails()) {
                return DataReturnService::returnError(1000,'验证错误！',$validator->errors());
            }

            $userInfo = Base::getUserByToken($postData['token']);
            if($userInfo['code'] != '666'){
                return $userInfo;
            }
            $user   = $userInfo['data'];
            DB::table('share_product_miniapp')->insert([
                'user_id'        =>$user['id'],
                'parent_id'      =>$postData['parent_id'],
                'product_id'     =>$postData['product_id'],
                'product_url'    =>$request->post('product_url'),
                'miniapp_url'    =>$request->post('miniapp_url'),
                'state'           =>0,
                'create_time'    =>date('Y-m-d H:i:s'),
                'update_time'    =>date('Y-m-d H:i:s'),
            ]);
            return DataReturnService::returnOk([''],'记录分享成功');
        }



}